import { useEffect, useState } from 'react'
import dayjs, { Dayjs } from 'dayjs'
import {
  Button,
  Card,
  Col,
  DatePicker,
  Drawer,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
  Space,
  Typography,
} from 'antd'

import { selectFilterOption } from '@/utils/utils'
import { EventSelect } from '@oBiz/components/EventSelect'
import { IEventTemplateEnableRes } from '@oBiz/components/EventSelect/api'
import { useCountries } from '@oBiz/hooks/SWRApi/useCountries'
import { useTimeZoneList } from '@oBiz/hooks/SWRApi/useTimeZone'
import { apiWaybillRecordAddressInfo } from '@oBiz/TrackManage/List/apis'
import { apiSetPublishEvent } from '../../apis'
import { ISetPublishEventReq } from '../../interface'
import { useBoundStore } from '../../store'
import { getLocationTypeName, useUrlParams } from '../../utils'
import { popupSlot } from './utils'
import styles from './styles.module.less'

const updatePopup = popupSlot.insert(null)

export interface IAddEventProps {
  success?: (val: any) => void
}

type IFormValue = Omit<ISetPublishEventReq, 'currentEdd' | 'eventTime' | 'updateEdd' | 'nextUpdateTime'> & {
  eventTemplate: IEventTemplateEnableRes
  statusGroup?: number
  status?: number
  locationType?: number
  currentEdd?: Dayjs
  eventTime?: Dayjs
  updateEdd?: Dayjs
  nextUpdateTime?: Dayjs
}

export const AddEvent = Object.assign(
  ({ destroy, success }: IAddEventProps & { destroy: () => void }) => {
    const { waybillNo } = useUrlParams()
    const { open, onHide, afterOpenChange } = popupSlot.useAntdPopupAnimation(destroy)
    const countriesRes = useCountries()
    const detail = useBoundStore(state => state.detail)
    const getDetail = useBoundStore(state => state.getDetail)
    const getEventList = useBoundStore(state => state.getEventList)
    const getWaybillStatusOverview = useBoundStore(state => state.getWaybillStatusOverview)
    const [form] = Form.useForm<IFormValue>()
    const [fetching, setFetching] = useState(false)
    const timeZoneRes = useTimeZoneList()

    const getWaybillRecordAddressInfo = async ({
      eventTemplateId,
      waybillNo,
    }: {
      eventTemplateId?: number
      waybillNo?: string
    }) => {
      if (!eventTemplateId || !waybillNo) return
      const publishPathIDTOS = [
        {
          waybillNo,
          eventTemplateId: Number(eventTemplateId),
        },
      ]
      const res = await apiWaybillRecordAddressInfo({ publishPathIDTOS })
      form.setFieldsValue({
        ...(res?.[0].addressListODTO || {}),
      })
    }

    const onValuesChange = (values: ISetPublishEventReq & { eventTemplate: IEventTemplateEnableRes }) => {
      if (values?.eventTemplate) {
        getWaybillRecordAddressInfo({
          eventTemplateId: values.eventTemplate?.eventTemplateId,
          waybillNo,
        })
        form.setFieldsValue({
          locationType: values.eventTemplate?.locationType,
          statusGroup: values.eventTemplate?.statusGroup,
          status: values.eventTemplate?.status,
        })
      }
    }

    useEffect(() => () => form.resetFields(), [])

    const resetForm = () => {
      form.resetFields()
      form.setFieldsValue({
        currentEdd: detail?.edd ? dayjs(detail.edd) : undefined,
        updateEdd: detail?.edd ? dayjs(detail.edd) : undefined,
      })
    }

    useEffect(() => {
      if (detail) {
        form.setFieldsValue({
          currentEdd: detail?.edd ? dayjs(detail.edd) : undefined,
          updateEdd: detail?.edd ? dayjs(detail.edd) : undefined,
        })
      }
    }, [detail])

    return (
      <Drawer
        styles={{ header: { backgroundColor: 'var(--fba-bg)' }, body: { backgroundColor: 'var(--fba-bg)' } }}
        title={`添加轨迹-${waybillNo}`}
        width={800}
        open={open}
        onClose={onHide}
        afterOpenChange={afterOpenChange}
        footer={
          <div className={styles.footer}>
            <Space>
              <Button onClick={resetForm}>重置</Button>
              <Button onClick={onHide}>取消</Button>
              <Button
                type="primary"
                onClick={async () => {
                  await form.validateFields()
                  const { eventTemplate, updateEddZone, eventTime, currentEdd, updateEdd, nextUpdateTime, ...values } =
                    form.getFieldsValue(true)
                  Modal.confirm({
                    title: `确认要添加轨迹吗？`,
                    okButtonProps: { loading: fetching },
                    onOk: async () => {
                      try {
                        setFetching(true)
                        await apiSetPublishEvent({
                          ...values,
                          eventTime: eventTime?.format($F_YMDHms),
                          currentEdd: currentEdd?.format($F_YMD),
                          updateEdd: updateEdd?.format($F_YMD),
                          nextUpdateTime: nextUpdateTime?.format($F_YMD),
                          waybillNo,
                          eventTemplateId: eventTemplate?.eventTemplateId,
                          updateEddZone,
                          nextUpdateAndEddZone: updateEddZone,
                          eventTimeZone: updateEddZone,
                          currentEddZone: updateEddZone,
                        })
                        message.success(`添加轨迹成功`)
                        await getEventList(waybillNo)
                        await getWaybillStatusOverview(waybillNo)
                        await getDetail()
                        onHide()
                      } finally {
                        setFetching(false)
                      }
                    },
                  })
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <Card>
          <Form form={form} layout="vertical" onValuesChange={onValuesChange}>
            <Form.Item name="eventTemplate" label="轨迹模版" rules={[{ required: true, message: '请输入中文描述' }]}>
              <EventSelect />
            </Form.Item>
            <Form.Item name="eventTime" label="发生时间" rules={[{ required: true, message: '请选择发生时间' }]}>
              <DatePicker
                showTime
                format={$F_YMDHms}
                style={{ width: '100%' }}
                disabledDate={current => current && current > dayjs().endOf('day')}
              />
            </Form.Item>
            <Form.Item
              name="locationType"
              label="Location类型"
              rules={[{ required: true, message: '请选择Location类型' }]}
            >
              <Select
                placeholder="请选择Location类型"
                disabled
                options={getLocationTypeName.valueList.map(value => ({
                  label: getLocationTypeName(value),
                  value,
                }))}
              />
            </Form.Item>
            <Typography.Title level={5}>详细地址信息</Typography.Title>
            <Form.Item name="street1" label="Street1">
              <Input style={{ width: '100%' }} placeholder="街道地址第一行" />
            </Form.Item>
            <Form.Item name="street2" label="Street2">
              <Input style={{ width: '100%' }} placeholder="街道地址第二行" />
            </Form.Item>
            <Row gutter={[24, 0]}>
              <Col span={12}>
                <Form.Item name="city" label="City" rules={[{ required: true, message: '请输入城市' }]}>
                  <Input style={{ width: '100%' }} placeholder="城市" />
                </Form.Item>
                <Form.Item name="postalCode" label="PostalCode">
                  <Input style={{ width: '100%' }} placeholder="邮政编码" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="stateProvince"
                  label="StateProvince"
                  rules={[{ required: true, message: '请输入州/省' }]}
                >
                  <Input style={{ width: '100%' }} placeholder="州/省" />
                </Form.Item>
                <Form.Item
                  name="countryCode"
                  label="CountryCode"
                  rules={[{ required: true, message: '请选择国家代码' }]}
                >
                  <Select
                    style={{ width: '100%' }}
                    placeholder="国家代码"
                    loading={countriesRes.loading}
                    options={countriesRes.data?.list.map(d => ({ label: d.code, value: d.code }))}
                    filterOption={selectFilterOption}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[24, 0]}>
              <Col span={6}>
                <Form.Item name="currentEdd" label="现EDD">
                  <DatePicker style={{ width: '100%' }} disabled />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item noStyle shouldUpdate={(values, prevValues) => values.eventTime !== prevValues.eventTime}>
                  {({ getFieldValue }) => {
                    const eventTime = getFieldValue('eventTime') || dayjs()
                    return (
                      <Form.Item
                        name="updateEdd"
                        label="更新EDD"
                        rules={[{ required: true, message: '请选择更新EDD日期' }]}
                      >
                        <DatePicker
                          style={{ width: '100%' }}
                          disabledDate={current => {
                            if (!current) return true
                            const afterNow = current.isAfter(dayjs(), 'day')
                            const afterEvent = current.isAfter(eventTime, 'day')
                            const beforeLimit = current.isBefore(eventTime.add(91, 'day'), 'day')
                            // 仅允许：> 今天、> 事件时间、< 事件时间+90天；其他日期禁用
                            return !(afterNow && afterEvent && beforeLimit)
                          }}
                        />
                      </Form.Item>
                    )
                  }}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="updateEddZone" label="时区" rules={[{ required: true, message: '请选择时区' }]}>
                  <Select
                    style={{ width: '100%' }}
                    placeholder="时区"
                    loading={timeZoneRes.loading}
                    options={timeZoneRes.data?.list?.map(d => ({ label: d.utcOffset, value: d.utcOffset }))}
                    filterOption={selectFilterOption}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  noStyle
                  shouldUpdate={(values, prevValues) => {
                    return values.currentEdd !== prevValues.currentEdd || values.updateEdd !== prevValues.updateEdd
                  }}
                >
                  {({ getFieldValue }) => {
                    const currentEdd = getFieldValue('currentEdd')
                    const updateEdd = getFieldValue('updateEdd')
                    const diffDay = currentEdd ? dayjs(updateEdd).diff(dayjs(currentEdd), 'day') : 0
                    return (
                      <Form.Item label="变化">
                        <Input style={{ width: '100%' }} disabled value={diffDay === 0 ? '无变化' : diffDay} />
                      </Form.Item>
                    )
                  }}
                </Form.Item>
              </Col>
            </Row>
            <Form.Item name="nextUpdateTime" label="下次更新时间">
              <DatePicker
                style={{ width: '100%' }}
                disabledDate={current => current && current.isBefore(dayjs(), 'day')}
              />
            </Form.Item>
            <Form.Item name="note" label="备注">
              <Input.TextArea
                autoSize={{ minRows: 6 }}
                placeholder="请输入备注"
                style={{ width: '100%' }}
                maxLength={100}
                showCount
              />
            </Form.Item>
          </Form>
        </Card>
      </Drawer>
    )
  },
  {
    open: ({ success }: IAddEventProps) => {
      updatePopup(<AddEvent destroy={() => updatePopup(null)} success={success} />)
    },
  },
)
